﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections;
using Bll;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;

namespace StockServer
{
    public partial class ServerStock : DevExpress.XtraEditors.XtraForm
    {
#region
        private Hashtable htAcGroupUsd = new Hashtable();
        private Hashtable htAcGroupImm = new Hashtable();
        StrRespon sr = new StrRespon();
        //// 用于监听接纳客户端连接的Socket
        //private Socket serverSocket;
        ////服务器端监听线程
        //private string strErrCommand;
        //private string strFunction;
        //private Thread serverThread;
        //private AsyncCallback callbackOnAccept;
        //private AsyncCallback callbackOnRecv;
        //private AsyncCallback callbackOnSend;
        //private byte[] recvBuf = new byte[1024 * 5];
        // 用于和客户端进行通讯的Socket列表，以客户端GUID作为key
        //private Hashtable clients = new Hashtable();
        //客户登陆列表，以GUID为KEY
        public Hashtable htUsers = new Hashtable();
        //客户登陆列表，以客户名字作为KEY
        public Hashtable htOnline = new Hashtable();
        //营业员登陆列表，以GUID为KEY
        public Hashtable htAss = new Hashtable();
        //所有客户详细资料信息，以客户名字为KEY
        public Hashtable htCustomers = new Hashtable();
        //发送商品信息客户端集合
        public ArrayList alClients = new ArrayList();

        System.Net.IPEndPoint endPoint;

        //保存登陆客户IP 登陆时间
        public Hashtable htClientDetails = new Hashtable();
        private DataTable dtCustomer = new DataTable();
        private DataTable dtLimitNew;
        private DataTable dtLimitLiq;
        string TRAD_DATE;
        private Hashtable htOrderDetails = Hashtable.Synchronized(new Hashtable());

        private Hashtable htItemDetails = new Hashtable();
        private long key = 10000;
        private DataTable dtItem;
        private string strItemPrice = "";
        private string strItemDetails = "";

        ClientUser clientuserinfo=new ClientUser();
     #endregion
        private DateTime oldTime = DateTime.Now;
        //string serviceip;
        //string servericeport;
        private delegate void writemessage(string msg);

        public ServerStock()
        {
            InitializeComponent();
            this.skinEngine1.SkinFile = Application.StartupPath + @"\DiamondGreen.ssk";
        }

        // 监听到客户端的连接请求的时候执行
        #region
        //private void OnAccept(IAsyncResult asynResult)
        //{
        //    WriteOut("Processing connect request... ");
        //    // 获取和该客户端通讯的Socket
        //    if (serverSocket == null)
        //    {
        //        this.InitializeServer();
        //    }
            
        //    Socket so = serverSocket.EndAccept(asynResult);
        //    WriteOut("Client connected, came from " + so.RemoteEndPoint.ToString());
        //    string guidclient = System.Guid.NewGuid().ToString();
           
        //    clients.Add(guidclient, so);
        //    ClientDetails cd = new ClientDetails();
        //    cd.strIP = so.RemoteEndPoint.ToString();
        //    cd.strLoginTime = DateTime.Now.ToShortTimeString();
           
        //    htClientDetails.Add(guidclient, cd);
        //    // 开始监听这个客户端
        //    so.BeginReceive(this.recvBuf, 0, 1024 * 5, SocketFlags.None, this.callbackOnRecv, guidclient);
        //    //继续监听连接
        //    this.serverSocket.BeginAccept(this.callbackOnAccept, serverSocket);
        //    // 继续监听连接
        //    WriteOut("Connection established, continue listening...");
        //    SendStatus ss = new SendStatus(so,guidclient);

        //    byte[] bytesMsg = Encoding.GetEncoding("GB2312").GetBytes(guidclient);
        //    so.BeginSend(bytesMsg,0,bytesMsg.Length,SocketFlags.None,this.callbackOnSend,ss);

        //}
        #endregion
        // 接收到来自客户端的数据
        #region
        //private void ReceiveCallback(IAsyncResult asResult)
        //{
        //    string clientGuid = asResult.AsyncState.ToString();
        //    try 
        //    {
        //        Socket client = (Socket)this.clients[clientGuid];
               
        //        if (client != null)
        //        {
        //            int bytesCount = client.EndReceive(asResult);
        //            if (bytesCount > 0)
        //            {
        //                string msg = Encoding.GetEncoding("GB2312").GetString(this.recvBuf, 0, bytesCount);
                         
        //                WriteOut("Client[" + clientGuid + "] : " + msg);

        //                if (msg.Trim() == "break")
        //                {
        //                    ProcessBreak(clientGuid);
        //                    return;
        //                }  
        //                    this.cmdSelect(clientGuid, msg);
        //                    client.BeginReceive(this.recvBuf, 0, 1024 * 5, SocketFlags.None, this.callbackOnRecv, clientGuid);
                     
        //            }
        //            else
        //            {
        //                this.alClients.Remove(clientGuid);
        //                this.clients.Remove(clientGuid);
        //                htOnline.Remove(htUsers[clientGuid].ToString());
        //                this.htUsers.Remove(clientGuid);
        //                this.htAss.Remove(clientGuid);
        //                this.htClientDetails.Remove(clientGuid);
        //                WriteOut("Client[" + clientGuid + "] disconnected");
        //                this.getOnline();
        //            }

        //        }
        //        else
        //        {
        //            this.alClients.Remove(clientGuid);
        //            this.clients.Remove(clientGuid);
        //            htOnline.Remove(htUsers[clientGuid]);
        //            this.htUsers.Remove(clientGuid);
        //            this.htAss.Remove(clientGuid);
        //            this.htClientDetails.Remove(clientGuid);
        //            WriteOut("Client[" + clientGuid + "] disconnected");
        //            this.getOnline();
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        ex.GetBaseException();
        //    }

        //}

        //private void ProcessBreak(string clientGuid)
        //{
        //    if (clients.Contains(clientGuid))
        //    {
        //        ((Socket)clients[clientGuid]).Close();
        //        this.clients.Remove(clientGuid);
        //    }
        //    if (htUsers.ContainsKey(clientGuid) && htOnline.ContainsKey(htUsers[clientGuid].ToString()))
        //    {
        //        htOnline.Remove(htUsers[clientGuid].ToString());

        //    }
        //    if (htUsers.ContainsKey(clientGuid))
        //    {
        //        this.htUsers.Remove(clientGuid);

        //    }
        //    if (htAss.ContainsKey(clientGuid))
        //    {
        //        this.htAss.Remove(clientGuid);
        //    }
        //    if (alClients.Contains(clientGuid))
        //    {
        //        this.alClients.Remove(clientGuid);
        //    }
        //    if (htClientDetails.ContainsKey(clientGuid))
        //    {
        //        this.htClientDetails.Remove(clientGuid);
        //    }
        //    return;
        //}
        #endregion

        // 异步消息发送的回应
        #region
        //private void SendCallback(IAsyncResult asResult)
        //{
        //    try
        //    {
        //        SendStatus ss = (SendStatus)asResult.AsyncState;
        //        int bytesCount = ss.Client.EndSend(asResult);
        //        WriteOut(bytesCount + " bytes have been sent.the message is :" + ss.Message);
        //    }
        //    catch(Exception ex)
        //    {
        //        ex.GetBaseException();
        //    }
        //}
        #endregion

        //得到在线客户信息
        //private void getOnline()
        //{
        //    strFunction = "getOnline";
        //    string strSend = "online@";
        //    foreach (object o in htUsers.Keys)
        //    {
        //        if (htOnline.ContainsValue(o.ToString()))
        //        {
        //            strSend += htUsers[o].ToString() + "$" + ((ClientDetails)htClientDetails[o.ToString()]).strIP + "$" + ((ClientDetails)htClientDetails[o.ToString()]).strLoginTime + "#";
        //        }
        //    }
        //    strSend = strSend.TrimEnd('#');
        //    foreach (object o in htAss.Keys)
        //    {
        //        this.SendMsg(o.ToString(), strSend);
        //    }

        //}
        	//判断命令行
        //public void cmdSelect(string clientGuid, string strMsgs)
        //{

        //    string[] msgs = strMsgs.Trim().Split('\n');

        //    foreach (string msg in msgs)
        //    {

        //        string strChid = msg;
        //        if (strChid.IndexOf("@") != -1)
        //        {
        //            string[] cmd = strChid.Trim().Split('@');
        //            strErrCommand = cmd[0];
        //            switch (cmd[0])
        //            {
                       
        //                //用户登陆
        //                case "user":
        //                    userCheck(clientGuid, cmd[1]);
        //                    break;
        //                case "chPwd":

        //                    break;
        //            }
        //        }
        //    }

        //}

       //检查用户是否合法
        private void userCheck(string clientGuid, string msg)
        {
            string send = "";
            bool isok = true;
            string[] userDetails = msg.Trim().Split(':');
            isok=clientuserinfo.isOkUser(userDetails[0].ToString(), userDetails[1].ToString());
            if (isok)
            {

               DataSet ds = clientuserinfo.writerxmlinfo(userDetails[0].ToString());
               ds.WriteXml(Application.StartupPath + @"\Mytest.xml");
                string fileName = Application.StartupPath + @"\Mytest.xml";             
                FileStream fs = new FileStream(fileName, FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                StringBuilder getfile=new StringBuilder();
                getfile.Append("@");
                while (sr.Peek()>-1)
                {
                    getfile.Append(sr.ReadLine());
                }
                getfile.Append("@");
                string getnowstringfile = getfile.ToString();
                fs.Close();
                //this.SendMsg(clientGuid, getnowstringfile);

                send = "#success";
                //this.SendMsg(clientGuid, send);
            }
            else
            {
                send = "#failuser";
                //this.SendMsg(clientGuid, send);
            }

        }

        private void ServerStock_Load(object sender, EventArgs e)
        {
            //ReadIni readini = new ReadIni(Application.StartupPath + @"\\Config.ini");
            //if (readini.ExistINIFile())
            //{
            //    serviceip = readini.IniReadValue("Main", "serviceIP").ToString();
            //    servericeport = readini.IniReadValue("Main", "remotePort").ToString();
            //    callbackOnAccept = new AsyncCallback(this.OnAccept);
            //    callbackOnRecv = new AsyncCallback(this.ReceiveCallback);
            //    callbackOnSend = new AsyncCallback(this.SendCallback);
            //}
            //else
            //{
            //    MessageBox.Show("File is not exist!");

            //    this.Close();
            //}
        }


        public class ClientDetails
        {
            public string strIP;
            public string strLoginTime;
        }

        public class SendStatus
        {
            public SendStatus(Socket client, string msg)
            {
                this.Client = client;
                this.Message = msg;
            }
            public Socket Client;
            public string Message;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (this.btnStart.Text.Equals("Start"))
            {
                timer2.Enabled = true;
                this.btnStart.Enabled = false;
                this.InitializeServer();
                this.btnStart.Text = "Stop";
                this.btnStart.Enabled = true;
            }
            else
            {
                timer2.Enabled = false;
                string strSend = "jurisdiction@offLine#";
                foreach (object o in htOnline.Values)
                {
                    //this.SendMsg(o.ToString(), strSend);
                }
                this.btnStart.Enabled = false;
                this.StopServer();
                this.btnStart.Text = "Start";
                this.btnStart.Enabled = true;

            }
        }
        //定义委托实现写入文本
        private void truewriteout(string msg)
        {
            this.outTextBox.AppendText(msg);
            this.outTextBox.AppendText("\n");

        }
        private void WriteOut(string msg)
        {
           
           writemessage mywritmessage = new writemessage(truewriteout);
           this.Invoke(mywritmessage, new object[] {msg });         
           
        }
        private void StopServer()
        {
            //if (this.serverThread != null && this.serverThread.ThreadState != ThreadState.Aborted && this.serverThread.ThreadState != ThreadState.Stopped)
            //    this.serverThread.Abort();
            //if (clients.Count > 0)
            //    foreach (Socket client in this.clients.Values)
            //    {
            //        client.Shutdown(SocketShutdown.Both);
            //        client.Close();

            //    }

            //if (this.serverSocket != null)
            //{
            //    if (serverSocket.Connected)
            //    {
            //        serverSocket.Disconnect(false);
            //    }
            //    serverSocket.Close();
            //    serverSocket = null;
            //    //i
            //    //serverSocket.Shutdown(SocketShutdown.Both);
            //    //serverSocket.Close();

            //}
            // +++++++++ 新加入的代码 ++++++++++
            server.Close();
            outTextBox.Text = "";
            //this.clients.Clear();
        }
        AsySocket server = AsySocket.CreateInstance();
        private void InitializeServer()
        {
            server.MsgRecivedEvt += new OnMsgRecivedDelegate(server_MsgRecivedEvt);
            server.BeginListening();

        }

        void server_MsgRecivedEvt(string msg)
        {
            this.outTextBox.AppendText("\n" + msg);
        }
        // 主监听线程
        //private void ListenThreadRun()
        //{
        //    if (endPoint != null)
        //    {
        //        endPoint = null;
        //    }
        //   endPoint = new IPEndPoint(IPAddress.Parse(serviceip), int.Parse(servericeport));                  
        //   this.serverSocket.Bind(endPoint);
        //   serverSocket.Listen(1000);
        //   WriteOut("Begin listening at" + endPoint.ToString() + "...");
        //   this.serverSocket.BeginAccept(this.callbackOnAccept, serverSocket);             
        //}

        // 开始异步消息发送
        #region
        //private void SendMsg(string clientGuid, string msg)
        //{
        //    try
        //    {
        //       //msg = "\n" + msg;//sm.Encrypto(msg,clientGuid);
        //        Socket client = (Socket)clients[clientGuid];
        //        byte[] bytesMsg = Encoding.GetEncoding("GB2312").GetBytes(msg);
             
        //        SendStatus ss = new SendStatus(client, msg);              
        //        client.BeginSend(bytesMsg, 0, bytesMsg.Length, SocketFlags.None, this.callbackOnSend, ss);
        //    }
        //    catch(Exception ex)
        //    {
        //        ex.GetBaseException();
        //    }
            
        //}
        #endregion
        private void timer2_Tick(object sender, EventArgs e)
        {

        }

        private void ServerStock_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.StopServer();
        }

       
        private void 新增用户ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserGroupInfoCustomer ugc = new UserGroupInfoCustomer();
            NavItemClick(ugc);
        }

        /// <summary>
        /// 打开窗体
        /// </summary>
        /// <param name="p_Frm"></param>
        private void NavItemClick(Form p_Frm)
        {
            foreach (Form frm in this.MdiChildren)
            {
                if (frm.Name == p_Frm.Name)
                {
                    frm.Activate();
                    return;
                }
            }

            OpenChildForm(p_Frm);

        }

        /// <summary>
        /// 打开MDI子窗体
        /// </summary>
        /// <param name="p_Frm">MDI子窗体</param>
        private void OpenChildForm(Form p_Frm)
        {
            p_Frm.MdiParent = this;

            p_Frm.Show();
        }

        private void 用户组ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //客户端登录把登录信息发送给服务端通过验证，如果合格则服务端不停的接收客户端发送过来的信息，处理好后把信息返回给客户端这样的一个过程

            UserEdit uet = new UserEdit();
            NavItemClick(uet);

        }

        private void 差价信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SpredInfo si = new SpredInfo();
            NavItemClick(si);

        }

        private void 用户修改组ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserGroupInfo ugi = new UserGroupInfo();
            NavItemClick(ugi);
        }
    }
}